package com.xuan.configuration.properties;

import com.xuan.configuration.exception.SystemException;
import com.xuan.configuration.result.ResponseResultEnum;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * 数据加密解密
 */
@Setter
@Component
@ConfigurationProperties(prefix = "xuan.encryption")
public class Encryption {

    /**
     * 算法
     */
    private String algorithm;

    /**
     * 密钥
     */
    private String key;

    /**
     * 密钥大小
     */
    private int keySize;

//****************************************************************************************************************************************************

    /**
     * 数据加密
     *
     * @param data 数据
     * @return 加密的数据
     */
    public String encrypt(String data) {

        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), algorithm);
            Cipher cipher = Cipher.getInstance(algorithm);
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] encryptedBytes = cipher.doFinal(data.getBytes());
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            throw new SystemException(ResponseResultEnum.ENCRYPT_ERROR); // 数据解密失败
        }

    }

    /**
     * 数据解密
     *
     * @param encryptedData 加密的数据
     * @return 解密的数据
     */
    public String decrypt(String encryptedData) {

        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), algorithm);
            Cipher cipher = Cipher.getInstance(algorithm);
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
            return new String(decryptedBytes);
        } catch (Exception e) {
            throw new SystemException(ResponseResultEnum.DECRYPT_ERROR); // 数据解密失败
        }

    }

    public String generateKey() {

        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);
            keyGenerator.init(keySize);
            SecretKey secretKey = keyGenerator.generateKey();
            return Base64.getEncoder().encodeToString(secretKey.getEncoded());
        } catch (Exception e) {
            throw new SystemException(ResponseResultEnum.DECRYPT_ERROR); // 数据解密失败
        }

    }


}